package org.budo.dubbo.protocol.http.dispatcher.cometd;

import java.io.InputStream;
import java.text.ParseException;

import org.budo.support.lang.util.IoUtil;
import org.cometd.bayeux.server.ServerMessage.Mutable;
import org.cometd.server.JettyJSONContextServer;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;

/**
 * @author lmw
 */
public class CometdJsonContext extends JettyJSONContextServer {
    private static final Logger log = LoggerFactory.getLogger(CometdJsonContext.class);

    /**
     * [{"id":"7","channel":"/request","data":{"requestId":2,"interfaceName":"UserApi","methodName":"findById","args":[{"id":5}]},"clientId":"21np42b70m2rcpg5qgh0khf8nf"}]
     */
    @Override
    public Mutable[] parse(String json) throws ParseException {
        Mutable[] mutables = null;
        try {
            mutables = super.parse(json);
            return mutables;
        } catch (Throwable e) {
            log.error("#29 parse error, json=" + json + ", mutables=" + mutables + ", e=" + e, e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public String generate(Mutable message) {
        Object messageData = null;
        String messageString = null;

        try {
            messageData = message.getData();
            if (null == messageData || !(messageData instanceof InputStream)) {
                return super.generate(message);
            }

            InputStream inputStream = (InputStream) messageData;
            messageString = IoUtil.toString(inputStream);
            return "{\"channel\":\"" + message.getChannel() + "\",\"data\":" + messageString + "}";
        } catch (Throwable e) {
            log.error("#49 generate error, message=" + message + ", messageData=" + messageData + ", messageString=" + messageString + ", e=" + e, e);
            throw new RuntimeException(e);
        }
    }
}